<template>
    <view>
        <NavBar title="安全监测" add="新增" @redirect="redirect" />
        <view class="store-list" v-if="tabIndex == 1">
                <uv-drop-down ref="dropDown" sign="dropDown_1" text-active-color="#3c9cff"
                    :extra-icon="{ name: 'arrow-down-fill', color: '#666', size: '26rpx' }"
                    :extra-active-icon="{ name: 'arrow-up-fill', color: '#3c9cff', size: '26rpx' }"
                    :defaultValue="defaultValue" :custom-style="{ padding: '0 5rpx' }" @click="selectMenu">
                    <uv-drop-down-item name="materialOrder" type="2" :label="dropItem('materialOrder').label"
                        :value="dropItem('materialOrder').value" class="drop-down-item">
                    </uv-drop-down-item>
					<uv-drop-down-item  name="storeStatus" type="2" :label="dropItem('storeStatus').label"
					    :value="dropItem('storeStatus').value">
					</uv-drop-down-item>
                </uv-drop-down>
                <uv-drop-down-popup sign="dropDown_1" :click-overlay-on-close="true" :currentDropItem="currentDropItem"
                    @clickItem="clickItem"></uv-drop-down-popup>

            <scroll-view refresher-enabled="true" @refresherrefresh="refresherrefresh" :refresher-triggered='refresh' class="list" scroll-y @scrolltolower="scrolltolower">
                <view class="list-item" v-for="(item, index) in projectMaterialList" :key="index"
                    @click="monitorDetail(item)">
                    <view class="material-info">
						<view class="info-row project-row">
						    <text class="project-text">隐患描述</text>
						    <text class="project-content"> {{ item.dangerDesc }}</text>
						</view>
                        <view class="info-row project-row">
                            <text class="project-text">排查日期</text>
                            <text class="project-content"> {{ item.checkDate }}</text>
                        </view>
                        <view class="info-row project-row">
                            <text class="project-text">等级</text>
                            <text class="project-content"> {{ item.dangerLevel }}</text>
                        </view>
                        <view class="info-row project-row">
                            <text class="project-text">状态</text>
                            <text class="project-content"> {{ item.status==0?'未治理':item.status==1?'治理中':'已治理' }}</text>
                        </view>
<!--                        <view class="info-row project-row">
                            <text class="project-text">整改责任人</text>
                            <text class="project-content"> {{ item.changeName }}</text>
                        </view>
                        <view class="info-row project-row">
                            <text class="project-text">联系方式</text>
                            <text class="project-content"> {{ item.changeMobile }}</text>
                        </view> -->
						<view class="info-row project-row">
						    <text class="project-text">整改时间</text>
						    <text class="project-content"> {{ item.changeDate }}</text>
						</view>
                    </view>
                    <view class="material-header">
						<view class="pro-tag" @click.stop="monitorUpdate(item)">修改</view>
                        <view class="pro-tag" @click.stop="monitorRectify(item)">整改</view>
                        <view class="pro-tag" @click.stop="deleteMonitorItem(item)">
                            <text>删除</text>
                        </view>
                    </view>
                </view>
				<uv-modal ref="modal" title="删除" content='确认删除吗' align="center" @confirm="confirm" @cancel="cancelDel" :showCancelButton="true"></uv-modal>
                <!-- 没有更多数据提示 -->
                <view v-if="!noMore" class="no-more">
                    <uv-loading-icon status="noMore" :vertical="true"></uv-loading-icon>
                </view>

                <!-- 空数据提示 -->
                <!-- <view v-if="!loading && projectMaterialList.length === 0" class="empty">
                    <text>暂无数据</text>
                </view> -->
				<uv-empty mode="data" text="暂无数据" v-if="!loading && projectMaterialList.length === 0 && isempty" ></uv-empty>
            </scroll-view>
        </view>
		<!-- <image @click="redirect" class="add-but" src="/static/cl_add.png" mode=""></image> -->
    </view>
</template>
<script>
import NavBar from '@/components/NavBar/index.vue'
import {
    getmaterialSingle,
    getProjectList,
    // getsupplier,
    getsupplierAll,
    getProjectMaterial,
    getProjectQueryByParam,
	getMonitorList,
	deleteMonitor
} from '@/utils/app.js'
export default {
    components: {
        NavBar
    },
    onPageScroll() {
        // 滚动后及时更新位置
        this.$refs.dropDown.init();
    },
    computed: {
        dropItem(name) {
            return (name) => {
                const result = {};
                const find = this.result.find(item => item.name === name);
                if (find) {
                    result.label = find.label;
                    // 强制转数字
                    result.value = typeof find.value === 'string' && !isNaN(find.value) ? Number(find.value) : find
                        .value;
                } else {
                    result.label = this[name].label;
                    result.value = typeof this[name].value === 'string' && !isNaN(this[name].value) ? Number(this[
                        name].value) : this[name].value;
                }
                return result;
            }
        },
        // 获取当前下拉筛选项
        currentDropItem() {
            return this[this.activeName];
        },
    },
    data() {
        return {
			isempty:false,
			refresh:false,
            materialList: [],
            projectMaterialList: [],
            // 表示value等于这些值，就属于默认值
            defaultValue: [-1, 'all', '0'],
            // 筛选结果
            result: [{
                name: 'order',
                label: '最新发布',
                value: 'new'
            }],
            // { name: 'order', label: '最新发布', value: 'new' }
            activeName: 'projectOrder',
            projectOrder: {
                label: '项目',
                value: 'all',
                activeIndex: 0,
                color: '#333',
                activeColor: '#2878ff',
                child: [{
                    label: '综合排序',
                    value: 'all'
                }]
            },
            supplierOrder: {
                label: '供应商',
                value: 'all',
                activeIndex: 0,
                color: '#333',
                activeColor: '#2878ff',
                child: []
            },
            storeStatus: {
                label: '治理状态',
                value: 'all',
                activeIndex: -1,
                color: '#333',
                activeColor: '#2878ff',
                child: [
					{
					    label: '全选',
					    value: null
					},
					{
                    label: '未治理',
                    value: 0
                },
                {
                    label: '治理中',
                    value: 1
                },
                {
                    label: '已治理',
                    value: 2
                },
                ]
            },
            queryParams: {},
            tabList: [
                {
                    value: 1,
                    name: '项目材料'
                },
                {
                    value: 2,
                    name: '材料入库单',
                },
            ],
            tabIndex: 1,
            loading: false,
            noMore: false,
            isRefreshing: false,
            pageNum: 1,
            pageSize: 20,
            total: 0,
            pageData: {},
            materialOrder: {
                label: '项目名称',
                value: 'all',
                activeIndex: 0,
                color: '#333',
                activeColor: '#2878ff',
                child: []
            },
			currentItem: {}
        }
    },
    onShow() {
        // this.getProjectData()
		console.log('1111111',this.queryParams);
		if(this.queryParams.projectId){
			this.getProjectMaterialData()
		}else{
			this.getProjectQueryByParamData()
		}
        
    },
    // 触底加载
    // onReachBottom() {
    //     if (!this.loading && !this.noMore) {
    //         this.getProjectMaterialData();
    //     }
    // },
    //下拉刷新
    onPullDownRefresh() {
        if (this.isRefreshing) return;

        this.isRefreshing = true;
        this.pageNum = 1;
        this.noMore = false;
        this.projectMaterialList = [];
        // 显示刷新动画
        uni.showLoading({
            title: '刷新中...'
        });

        if (this.tabIndex == 1) {
            this.getProjectMaterialData().finally(() => {
                uni.hideLoading();
                uni.stopPullDownRefresh();
                this.isRefreshing = false;
            });
        } else {
            uni.hideLoading();
            uni.stopPullDownRefresh();
            this.isRefreshing = false;
        }

        this.getProjectData();

    },
    methods: {
		async refresherrefresh(){
			this.refresh = true
			this.pageNum = 1;
			this.noMore = false;
			this.projectMaterialList = [];
			// 显示刷新动画
			uni.showLoading({
			    title: '刷新中...'
			});
			
			if (this.tabIndex == 1) {
			    await this.getProjectMaterialData()
			} else {
			}
			
			 await this.getProjectData();
			 this.refresh = false
		},
		// 删除
		deleteMonitorItem(item) {
			this.$refs.modal.open();
			this.currentItem = item;
		},
		async confirm() {
			// 显示成功提示
			try {
				await deleteMonitor(this.currentItem.id);
				uni.showToast({
				  title: '删除成功',
				  icon: 'success'
				});
				this.pageNum = 1
				this.getProjectMaterialData();
			} catch (error) {
				uni.showToast({
				   title: '服务繁忙',
				   icon: 'error'
				});
			}
		},
		cancelDel(){
		},
		scrolltolower(){
			if(this.projectMaterialList.length>=this.total) return
			this.pageNum++
			if (!this.loading && !this.noMore) {
			        this.getProjectMaterialData();
			    }
		},
        enterStateNum(val) {
            if (val === '0') return '未入库'
            if (val === '1') return '已入库'
            return '入库撤回中'
        },
        getStatusTagClass(val) {
            if (val === '0') return 'status-blue'
            if (val === '1') return 'status-red'
            return 'status-yellow'
        },
        //获取项目列表
        getProjectData() {
            getProjectList().then(res => {
                if (res && res.code == 200) {
                    const projectOptions = res.rows.map(item => ({
                        label: item.projectName || item.name,
                        value: item.id
                    }));
                    // 更新项目下拉选项
                    this.projectOrder.child = [
                        ...projectOptions
                    ]
                    this.projectOrder.label = projectOptions[0].label
                    this.projectOrder.value = projectOptions[0].value
                    this.queryParams = {
                        projectId: projectOptions[0].value,
                        supplierType: 1
                    }
                    this.getsupplierData(this.queryParams)
                }
            })
        },
        //获取材料列表
        getmaterialSingleData(data) {
            getmaterialSingle(data).then(res => {
                if (res && res.code == 200) {
                    this.materialList = res.rows
                }
            })
        },
        //获取材料列表-项目
        getProjectQueryByParamData() {
            let data = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            }
            getProjectQueryByParam(data).then(res => {
                if (res && res.code == 200) {
                    const projectOptions = res.data.map(item => ({
                        label: item.projectName,
                        value: item.id
                    }));
                    this.materialOrder.child = [
                        ...projectOptions
                    ]

                    this.materialOrder.label = projectOptions[0].label
                    this.materialOrder.value = projectOptions[0].value
                    this.queryParams = {
                        projectId: projectOptions[0].value,
                    }
                    this.getProjectMaterialData()
                }
            })
        },
        //获取项目材料列表
        async getProjectMaterialData() {
            try {
                this.loading = true;
                let data = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    projectId: this.queryParams.projectId,
					status:this.queryParams.status
                }
				uni.showLoading({
					title: "加载中",
					mask: true
				});
                const res = await getMonitorList(data);
				uni.hideLoading();
                if (res?.code === 200) {
                    // 第一页覆盖，后续追加
                    this.projectMaterialList = this.pageNum == 1
                        ? res.rows
                        : [...this.projectMaterialList, ...res.rows];

                    this.total = res.total;
					if(this.projectMaterialList.length==0){
						this.isempty = true
					}else{
						this.isempty = false
					}

                    // 更准确的无更多数据判断
                    this.noMore = res.rows.length < this.pageSize ||
                        this.projectMaterialList.length >= this.total;

                    // if (!this.noMore) this.pageNum++;
                }
            } catch (error) {
                uni.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });

                // 失败时回退页码
                if (this.pageNum > 1) {
                    this.pageNum--;
                }
            } finally {
                this.loading = false;
            }
        },
        //供应商
        getsupplierData(data) {
            getsupplierAll(data).then(res => {
                if (res && res.code == 200) {
                    const supplierList = res.data.map(item => ({
                        label: item.name,
                        value: item.id
                    }));
                    this.supplierOrder.child = [
                        ...supplierList
                    ]
                    this.supplierOrder.label = supplierList[0].label
                    this.supplierOrder.value = supplierList[0].value
                    this.queryParams.supplierId = supplierList[0].value
                    this.getmaterialSingleData(this.queryParams)
                }
            })
        },
        
		redirect() {
			let data = this.queryParams;
			uni.navigateTo({
			  url: `/pages/monitor/add?projectId=${this.queryParams.projectId}`
			})
		},
        monitorDetail(item) {
            uni.navigateTo({
                url: `/pages/monitor/detail?id=${item.id}`
            })
        },
        //修改
        monitorUpdate(val) {
            uni.navigateTo({
                url: `/pages/monitor/add?id=${val.id}`
            })
        },
        //整改
        monitorRectify(val) {
            uni.navigateTo({
                url: `/pages/monitor/rectify?data=${val.id}`
            })
        },
        /**
         * 点击每个筛选项回调
         * @param {Object} e { name, active, type } = e
         */
        selectMenu(e) {
            const {
                name,
                active,
                type
            } = e;
            this.activeName = name;
            const find = this.result.find(item => item.name == this.activeName);
            if (find) {
                const findIndex = this[this.activeName].child.findIndex(item => item.label == find.label && item
                    .value == find.value);
                this[this.activeName].activeIndex = findIndex;
            } else {
                this[this.activeName].activeIndex = -1;
            }

        },
        /**
         * 点击菜单回调处理
         * @param {Object} item 选中项 { label,value } = e
         */
        clickItem(e) {
            let {
                label,
                value
            } = e;

            const findIndex = this.result.findIndex(item => item.name == this.activeName);
            if (this.defaultValue.indexOf(value) > -1 && this[this.activeName].label) {
                label = this[this.activeName].label;
            }
            // 更新 queryParams
            if (this.activeName === 'projectOrder') {
                this.queryParams.projectId = value;
            }
            if (this.activeName === 'supplierOrder') {
                this.queryParams.supplierId = value;
                this.getmaterialSingleData(this.queryParams);
            }
            if (this.activeName === 'storeStatus') {
                this.queryParams.enterState = value;
                this.getmaterialSingleData(this.queryParams);
                const val = Number(e.value)

                const idx = this.storeStatus.child.findIndex(item => item.value === val)
                this.storeStatus.activeIndex = idx
                this.storeStatus.value = val
                this.storeStatus.label = e.label
                // result里也存数字
                e.value = val
            }
            //项目材料
            if (this.activeName === 'materialOrder') {
                this.queryParams.projectId = value;
                this.projectMaterialList = []
                this.getProjectMaterialData()
            }
			if(this.activeName === 'storeStatus'){
				console.log(e);
				this.queryParams.status = value;
				this.projectMaterialList = []
				this.getProjectMaterialData()
			}
            // 已经存在筛选项
            if (findIndex > -1) {
                this.$set(this.result, findIndex, {
                    name: this.activeName,
                    label,
                    value
                })
            } else {
                this.result.push({
                    name: this.activeName,
                    label,
                    value
                });
            }
            this.result = this.result.filter(item => this.defaultValue.indexOf(item.value) == -1);
        },
        
    }
}
</script>

<style lang="scss" scoped>
* {
    box-sizing: border-box;
}

// ::v-deep .tab-sticky {
//     top: 0 !important;
// }
::v-deep.uv-text__value.uv-line-1{
		 max-width: 400rpx !important;
	}

.store-list {
    background-color: #E7E7E7;
    // padding: 15rpx 0;
}

.list {
    height: calc(100vh - 260rpx);
    background-color: #f6f7f9;
    padding-bottom: 20rpx;

    .list-item {
        margin: 20rpx auto 0;
        padding: 20rpx 30rpx;
        width: 690rpx;
        // height: 300rpx;
        background-color: #FFFFFF;
        border-radius: 30rpx;

        .status-tag {
            font-size: 24rpx;
            color: #F53F3F;
            background-color: #FFECE8;
            border-radius: 4px;
            padding: 4rpx 8rpx;
        }

        .status-blue {
            color: #2878ff !important;
            background-color: #e6f3ff !important;
        }

        .status-yellow {
            color: #ff9900 !important;
            background-color: #fff7e6 !important;
        }

        .material-header {
            display: flex;
            justify-content: right;
            margin-bottom: 20rpx;
        }

        .material-title {
            font-size: 32rpx;
            color: #242731;
            margin-right: 24rpx;
        }

        .material-code {
            font-size: 28rpx;
            color: #72767C;
        }

        .info-text {
            font-size: 24rpx;
            color: #72767C;
        }


        .info-row {
            display: flex;
            align-items: center;
        }

        .project-row {
            justify-content: space-between;
            padding: 8rpx 0;
        }

        .project-text {
            font-size: 30rpx;
            color: #242731;
			width: 140rpx;
			text-align: right;
			margin-right: 20rpx;
        }

        .project-content {
			flex: 1;
            font-size: 30rpx;
            color: #72767C;
			white-space: nowrap; 
			overflow: hidden; 
			text-overflow: ellipsis;
        }

        .pro-tag {
   //          font-size: 28rpx;
            
   //          border-radius: 4px;
   //          padding: 20rpx;
			margin-left: 40rpx;
			width: 124rpx;
			height: 72rpx;
			font-size: 30rpx;
			text-align: center;
			line-height: 72rpx;
			border-radius: 12rpx;
			color: #2878ff;
			background-color: #e6f3ff;
        }


    }

    .icon-image {
        width: 30rpx;
        height: 30rpx;
        margin-right: 10rpx;
    }
}

.add-but {
    width: 100rpx;
    height: 100rpx;
    position: fixed;
    bottom: 140rpx;
    right: 20rpx;
}

:deep(.uv-dp__container) {
    max-height: 40%;
    overflow-y: auto;
}

.empty {
    padding: 10rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
</style>